#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ford UK NGc2 爬虫Interior模块
专门处理内饰配置的抓取和数据提取
"""

import time
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, NoSuchElementException


class InteriorHandler:
    """Interior配置处理器"""
    
    def __init__(self, driver, wait, navigation_handler):
        """
        初始化Interior处理器
        
        Args:
            driver: WebDriver实例
            wait: WebDriverWait实例
            navigation_handler: 导航处理器实例
        """
        self.driver = driver
        self.wait = wait
        self.navigation_handler = navigation_handler
    
    def scrape_interior_data(self):
        """
        抓取Interior页面的数据
        
        Returns:
            list: 内饰选项列表
        """
        print("    🛋️ 开始抓取Interior选项...")
        
        try:
            # 步骤1：导航到Interior页面
            if not self.navigate_to_interior_page():
                print("    ❌ 无法进入Interior页面")
                return []
            
            # 步骤2：等待Interior页面加载
            print("    ⏳ 等待Interior页面加载...")
            time.sleep(3)
            
            # 步骤3：提取Interior选项
            interior_options = self.extract_interior_options()
            
            if interior_options:
                print(f"    ✅ 成功抓取到 {len(interior_options)} 个内饰选项")
                for i, interior in enumerate(interior_options, 1):
                    print(f"      {i}. {interior.get('name', 'Unknown')} - {interior.get('price', 'N/A')}")
            else:
                print("    ⚠️  未找到内饰选项")
                # 使用默认内饰数据
                interior_options = [
                    {"name": "Standard Interior", "price": "Standard"},
                    {"name": "Premium Interior", "price": "+£500"}
                ]
            
            return interior_options
            
        except Exception as e:
            print(f"    ❌ 抓取Interior数据时出错: {e}")
            return []
    
    def navigate_to_interior_page(self):
        """
        导航到Interior配置页面
        
        Returns:
            bool: 是否成功进入Interior页面
        """
        print(f"      🧭 导航到Interior页面...")
        
        try:
            # 方法1：查找导航栏中的Interior按钮
            nav_state = self.navigation_handler.get_navigation_state()
            if nav_state and 'Interior' in nav_state:
                interior_nav_info = nav_state['Interior']
                
                if (interior_nav_info.get('enabled', False) and 
                    not interior_nav_info.get('current', False)):
                    
                    interior_element = interior_nav_info['element']
                    print(f"      ✓ 找到Interior导航按钮")
                    
                    self.driver.execute_script("arguments[0].click();", interior_element)
                    time.sleep(2)
                    
                    if self.verify_interior_page_loaded():
                        print("      ✅ 通过导航栏进入Interior页面")
                        return True
            
            # 方法2：直接查找Interior相关链接
            interior_selectors = [
                'a[href*="interior"]',
                'button[data-testid*="interior"]',
                '[class*="interior"] a',
                'nav a:contains("Interior")'
            ]
            
            for selector in interior_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for element in elements:
                        if element.is_displayed() and element.is_enabled():
                            print(f"      ✓ 找到Interior链接: {selector}")
                            element.click()
                            time.sleep(2)
                            
                            if self.verify_interior_page_loaded():
                                print("      ✅ 通过直接链接进入Interior页面")
                                return True
                except Exception:
                    continue
            
            # 方法3：检查当前URL是否已经在Interior页面
            current_url = self.driver.current_url.lower()
            if 'interior' in current_url:
                print("      ✓ 当前URL显示已在Interior页面")
                return self.verify_interior_page_loaded()
            
            print("      ❌ 所有Interior导航方法都失败")
            return False
            
        except Exception as e:
            print(f"      ❌ 导航到Interior页面时出错: {e}")
            return False
    
    def verify_interior_page_loaded(self):
        """
        验证Interior页面是否已加载
        
        Returns:
            bool: 是否已加载Interior页面
        """
        try:
            # 检查方法1：查找Interior相关的页面元素（根据用户澄清的业务逻辑）
            interior_indicators = [
                'button[type="button"][class*="ButtonAsLink"]',  # 用户澄清的ButtonAsLink按钮
                'div[data-testid*="interior"]',
                '[class*="interior-option"]',
                'button[class*="InteriorOption"]',
                '[class*="ProductTile"][class*="Interior"]'
            ]
            
            for selector in interior_indicators:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    if elements:
                        print(f"        ✓ Interior页面验证成功: 找到 {len(elements)} 个Interior元素")
                        return True
                except Exception:
                    continue
            
            # 检查方法2：页面标题或URL
            current_url = self.driver.current_url.lower()
            page_title = self.driver.title.lower()
            
            if 'interior' in current_url or 'interior' in page_title:
                print("        ✓ Interior页面验证成功: URL或标题包含interior")
                return True
            
            # 检查方法3：导航状态
            nav_state = self.navigation_handler.get_navigation_state()
            if nav_state and 'Interior' in nav_state:
                if nav_state['Interior'].get('current', False):
                    print("        ✓ Interior页面验证成功: 导航状态显示当前在Interior页面")
                    return True
            
            print("        ❌ Interior页面验证失败")
            return False
            
        except Exception as e:
            print(f"        ❌ 验证Interior页面时出错: {e}")
            return False
    
    def extract_interior_options(self):
        """
        从Interior页面提取所有内饰选项
        根据用户澄清：只有ButtonAsLink按钮内容才是Interior
        
        Returns:
            list: 内饰选项列表
        """
        print("        🔍 开始提取Interior选项...")
        
        try:
            interior_options = []
            
            # 根据用户澄清的业务逻辑：ButtonAsLink按钮
            interior_selector = 'button[type="button"][class*="ButtonAsLink"]'
            
            # 查找所有ButtonAsLink按钮
            button_elements = self.driver.find_elements(By.CSS_SELECTOR, interior_selector)
            
            print(f"        找到 {len(button_elements)} 个ButtonAsLink按钮")
            
            for i, button_element in enumerate(button_elements, 1):
                if button_element.is_displayed():
                    interior_data = self.extract_interior_option_data(button_element)
                    if interior_data:
                        interior_options.append(interior_data)
                        print(f"          ✓ 提取Interior {i}: {interior_data['name']} - {interior_data['price']}")
            
            return interior_options
            
        except Exception as e:
            print(f"        ❌ 提取Interior选项时出错: {e}")
            return []
    
    def extract_interior_option_data(self, element):
        """
        从ButtonAsLink内饰选项元素中提取数据
        根据用户澄清：按钮内容作为Interior名称，同一P标签里的span作为价格
        
        Args:
            element (WebElement): ButtonAsLink内饰选项元素
            
        Returns:
            dict or None: 内饰选项数据
        """
        try:
            name = ''
            price = ''
            description = ''
            
            # 根据用户澄清的业务逻辑：按钮内容是Interior名称
            if element.tag_name.lower() == 'button' and 'ButtonAsLink' in element.get_attribute('class'):
                name = element.text.strip()
                
                # 查找同一P标签里的span价格信息
                try:
                    # 向上查找包含该按钮的P标签
                    p_element = element.find_element(By.XPATH, './ancestor::p[1]')
                    
                    # 在P标签内查找span价格元素
                    price_spans = p_element.find_elements(
                        By.CSS_SELECTOR, 
                        'span[class*="Attributes__AttributeBaseStyle"][class*="Attributes__AttributeValue"]'
                    )
                    
                    for span in price_spans:
                        span_text = span.text.strip()
                        if '£' in span_text:
                            price = span_text
                            break
                    
                    # 如果没找到特定的span，查找P标签内所有包含£的span
                    if not price:
                        all_spans = p_element.find_elements(By.CSS_SELECTOR, 'span')
                        for span in all_spans:
                            span_text = span.text.strip()
                            if '£' in span_text:
                                price = span_text
                                break
                
                except Exception as e:
                    print(f"            查找价格信息时出错: {e}")
                    # 备用方法：在按钮附近查找价格
                    try:
                        parent = element.find_element(By.XPATH, './parent::*')
                        price_elements = parent.find_elements(By.CSS_SELECTOR, '*:contains("£")')
                        for price_elem in price_elements:
                            price_text = price_elem.text.strip()
                            if '£' in price_text:
                                price = price_text
                                break
                    except Exception:
                        pass
            
            # 默认价格
            if not price:
                price = '£0'  # 根据用户澄清的示例，默认为£0
            
            # 提取描述信息（可选）
            if name and len(name) > 50:  # 如果按钮文本很长，可能包含描述
                lines = name.split('\n')
                if len(lines) > 1:
                    name = lines[0].strip()
                    description = ' '.join(lines[1:]).strip()
            
            if name:
                return {
                    'name': name,
                    'price': price,
                    'description': description,
                    'element': element
                }
            
            return None
            
        except Exception as e:
            print(f"          ❌ 提取Interior选项数据时出错: {e}")
            return None
    
    def update_car_objects_with_interior_data(self, car_series, target_model, interior_data):
        """
        使用Interior数据更新CarObject实例
        
        Args:
            car_series (CarSeries): 车系对象
            target_model (str): 目标车型名称
            interior_data (list): 内饰数据列表
        """
        print(f"    🔄 为 {target_model} 的CarObject添加Interior数据...")
        
        try:
            updated_objects = 0
            
            # 转换内饰数据为字符串列表（保持向后兼容）
            interior_names = []
            for interior in interior_data:
                interior_name = interior.get('name', '')
                interior_price = interior.get('price', '£0')
                
                # 格式：内饰名 (价格)
                if interior_price and interior_price != '£0':
                    interior_display = f"{interior_name} ({interior_price})"
                else:
                    interior_display = interior_name
                
                if interior_display:
                    interior_names.append(interior_display)
            
            # 遍历所有CarObject，找到匹配的车型
            for car_object in car_series.car_object_list:
                if car_object.model_name.lower() == target_model.lower():
                    # 替换原有的内饰数据
                    car_object.interiors = interior_names.copy()
                    updated_objects += 1
                    
                    print(f"      ✓ 为 {target_model} + {car_object.drive} 添加 {len(interior_names)} 个内饰选项")
            
            print(f"    ✅ 共更新了 {updated_objects} 个CarObject，添加了 {len(interior_names)} 个内饰选项")
            
        except Exception as e:
            print(f"    ❌ 更新CarObject时出错: {e}")